<template>
    <fieldset>
        <legend>三级联动</legend>
        省：
        <select name="" id="" v-model="code1"  @change="handleChange(code1)">
            <option v-for="item in provience" :key="item.id" :value="item.id">{{item.name}}</option>
        </select>
        &nbsp;&nbsp;

        市：
        <select name="" id="" v-model="code2" 
        @change="handleChange2(code2)">
            <option v-for="item in city" :key="item.id" :value="item.id">{{item.name}}</option>
        </select>

        县/区：
        <select name="" id="" v-model="code3">
            <option v-for="item in county" :key="item.id" :value="item.id">
            {{item.name}}</option>
        
        </select>
        
        

    </fieldset>
</template>
<script>
import * as api from "@/api/select"
export default{
        data(){
            return{
                provience:[],
                code1:1,
                city:[],
                code2:'',
                county:[],
                code3:''
            }
        },
        mounted(){
            api.fetchData()
            .then(res=>{
                console.log(res)
                this.provience=res
                let num =res[0].id
                this.handleChange(num)
            })
            
          
        },
        methods:{
            handleChange(num){
                console.log(num)
                api.fetchCity(num)
                .then(res=>{
                    console.log(res)
                    this.city=res
                    this.code2=res[0].id
                    // 添加判断条件 让每个城市的默认第一个id
                  let num1=res[0].id
                  this.handleChange2(num1)
                })
                
               
            },
            handleChange2(num1){
             api.fetchCounty(num1)
              .then(res=>{
                console.log(res)
                this.county=res
                this.code3=res[0].id
            })
               
            }
        
        }
    
}

</script>

<style scoped>
  select{
    width: 100px;
  }
</style>
